<template>
  <div class="page-container">
    <!--  v-auth="'system:report:query'" -->
    <el-form class="search-form" inline>
      <el-form-item>
        <el-input
          v-model="queryForm.userName"
          :prefix-icon="Search"
          clearable
          :placeholder="t('report.placeholders.enterUsername')"
          style="width: 160px"
        />
      </el-form-item>

      <el-form-item>
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="-"
          :start-placeholder="t('report.placeholders.startTime')"
          :end-placeholder="t('report.placeholders.endTime')"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          style="width: 240px"
          @change="onDateChange"
        />
      </el-form-item>

      <el-form-item>
        <el-select
          v-model="queryForm.riskLevelId"
          style="width: 160px"
          clearable
          :placeholder="t('report.placeholders.selectRiskLevel')"
        >
          <el-option
            v-for="item in dictData.riskLevelList || []"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-select
          v-model="queryForm.healthCategoryId"
          style="width: 160px"
          clearable
          :placeholder="t('report.placeholders.selectHealthCategory')"
        >
          <el-option
            v-for="item in dictData.healthCategoryList || []"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-select
          v-model="queryForm.statusId"
          style="width: 160px"
          clearable
          :placeholder="t('report.placeholders.selectStatusType')"
        >
          <el-option
            v-for="item in dictData.healthStatusList || []"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-select
          v-model="queryForm.attentionType"
          style="width: 160px"
          clearable
          :placeholder="t('report.placeholders.selectAttentionType')"
        >
          <el-option
            v-for="item in attentionTypeList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-select
          v-model="queryForm.medicalInstitution"
          style="width: 160px"
          clearable
          :placeholder="t('report.placeholders.selectHospital')"
        >
          <el-option
            v-for="item in dictData.medicalInstitutionList || []"
            :key="item.id"
            :label="item.name"
            :value="item.name"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-select
          v-model="queryForm.healthTagId"
          style="width: 160px"
          clearable
          :placeholder="t('report.placeholders.selectHealthTag')"
        >
          <el-option
            v-for="item in dictData.healthTagList || []"
            :key="item.tagId"
            :label="item.name"
            :value="item.tagId"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button @click="onReload">{{ t("report.reset") }}</el-button>
        <el-button type="primary" @click="onSearch">{{
          t("report.search")
        }}</el-button>
      </el-form-item>
    </el-form>

    <el-card shadow="never" class="table-card">
      <el-table
        v-loading="tableLoading"
        :data="tableData"
        size="small"
        border
        stripe
        row-key="id"
      >
        <el-table-column
          prop="reportNumber"
          :label="t('report.reportInfo')"
          min-width="120"
          show-overflow-tooltip
        />

        <el-table-column
          prop="userName"
          :label="t('report.userInfo')"
          min-width="120"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            {{ row.userName || "无" }}
          </template>
        </el-table-column>

        <el-table-column
          prop="attentionLevel"
          :label="t('report.userAttention')"
          width="150"
          align="center"
          sortable
        >
          <template #default="{ row }">
            <EditableRate
              v-model="row.attentionLevel"
              :data-type="1"
              :data-id="row.reportId"
            />
          </template>
        </el-table-column>

        <el-table-column
          prop="riskLevel"
          :label="t('report.riskLevel')"
          width="100"
          align="center"
        >
          <template #default="{ row }">
            <el-tag v-if="row.riskLevel === '良好'" type="success">{{
              row.riskLevel
            }}</el-tag>
            <el-tag v-else-if="row.riskLevel === '中风险'" type="warning">{{
              row.riskLevel
            }}</el-tag>
            <el-tag v-else-if="row.riskLevel === '高风险'" type="danger">{{
              row.riskLevel
            }}</el-tag>
            <el-tag v-else-if="row.riskLevel === '中高风险'" type="danger">{{
              row.riskLevel
            }}</el-tag>
            <el-tag v-else-if="row.riskLevel === '中度风险'" type="danger">{{
              row.riskLevel
            }}</el-tag>
            <el-tag v-else type="info">{{ row.riskLevel }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column
          prop="healthCategory"
          :label="t('report.healthCategory')"
          min-width="120"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <span
              :class="{
                'health-tag': true,
                'health-tag--sub': row.healthCategory === '亚健康人群',
                'health-tag--normal': row.healthCategory === '健康人群',
                'health-tag--chronic':
                  row.healthCategory === '慢性病人群' ||
                  row.healthCategory === '慢性病稳定期患者' ||
                  row.healthCategory === '院外恢复期人群' ||
                  row.healthCategory === '院外康复期人群',
                'health-tag--doctor':
                  row.healthCategory === '门诊就医人群' ||
                  row.healthCategory === '急诊就医人群',
                'health-tag--hospital': row.healthCategory === '住院就医人群'
              }"
            >
              {{ row.healthCategory }}
            </span>
          </template>
        </el-table-column>

        <el-table-column
          prop="abnormalIndicators"
          :label="t('report.abnormalIndicators')"
          min-width="200"
        >
          <template #default="{ row }">
            <div
              v-if="row.abnormalIndicators && row.abnormalIndicators.length > 0"
              :class="{
                'abnormal-indicators-container': true,
                'has-overflow': checkIfOverflow(row.abnormalIndicators)
              }"
            >
              <!-- 显示所有指标项目，让CSS控制显示行数 -->
              <div
                v-for="(item, index) in row.abnormalIndicators"
                :key="`${row.id}_${item.itemId || index}`"
                class="abnormal-indicators-item"
              >
                <span class="abnormalIndicators-name">{{ item.name }}</span>
              </div>
            </div>
            <span v-else style="color: #67c23a">指标一切正常</span>
          </template>
        </el-table-column>

        <el-table-column
          prop="imageDataCount"
          :label="t('report.imagingData')"
          width="90"
          align="center"
        >
          <template #default="{ row }">
            <el-button
              style="
                display: flex;
                align-items: center;
                justify-content: center;
              "
              type="primary"
              link
              @click="showImagingModal(row)"
            >
              <el-tag
                type="info"
                effect="plain"
                style="color: #409eff; border: none"
              >
                {{ row.imageDataCount }}
              </el-tag>
            </el-button>
          </template>
        </el-table-column>

        <el-table-column
          prop="institution"
          :label="t('report.hospitalInstitution')"
          min-width="150"
          show-overflow-tooltip
        />

        <el-table-column
          prop="reportCategory"
          :label="t('report.reportCategory')"
          width="200"
        >
          <template #default="{ row }">
            <span v-if="row.reportCategory === 1">体检报告</span>
            <span v-else-if="row.reportCategory === 2">健康报告</span>
            <span v-else>未知类别</span>
          </template>
        </el-table-column>

        <el-table-column
          prop="inspectionDate"
          sortable
          :label="t('report.inspectionDate')"
          width="100"
        />

        <el-table-column
          prop="reportStatusName"
          :label="t('report.reportStatus')"
          width="150"
          align="center"
        >
          <template #default="{ row }">
            <el-tag v-if="row.reportStatusName === '已通过'" type="success">{{
              row.reportStatusName
            }}</el-tag>
            <el-tag
              v-else-if="row.reportStatusName === '待审核'"
              type="warning"
              >{{ row.reportStatusName }}</el-tag
            >
            <el-tag v-else>{{ row.reportStatusName }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column :label="t('report.actions')" fixed="right" width="120">
          <template #default="{ row }">
            <div class="actions-container">
              <el-button
                type="primary"
                link
                size="small"
                @click="viewReport(row.reportId)"
              >
                {{ t("report.viewReport") }}
              </el-button>
              <el-button
                type="primary"
                link
                size="small"
                @click="compareReport(row)"
              >
                {{ t("report.compareReport") }}
              </el-button>
              <el-button
                type="primary"
                link
                size="small"
                @click="showHealthInfo(row)"
              >
                {{ t("report.writeSuggestion") }}
              </el-button>
              <el-button
                type="primary"
                link
                size="small"
                @click="addToTask(row)"
              >
                {{ t("report.addToTask") }}
              </el-button>
              <!-- v-auth="'system:report:track'" -->
              <el-button
                type="primary"
                link
                size="small"
                @click="viewReportTrack(row.familyId)"
              >
                {{ t("report.viewFamilyReport") }}
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryForm.pageNum"
          v-model:page-size="queryForm.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="queryReportList"
          @current-change="queryReportList"
        />
      </div>
    </el-card>
  </div>

  <!-- 影像资料弹窗 -->
  <ImagingDataModal ref="imagingModalRef" title="检查影像资料" width="1000px" />

  <!-- 健康信息抽屉 -->
  <JiankangDrawer
    ref="jiankangDrawerRef"
    title="健康信息详情"
    @save="onHealthInfoSave"
  />

  <!-- <AddTask ref="addTaskDrawerRef" title="添加随访计划" @save="onAddTaskSave" /> -->

  <!-- 任务计划弹窗 -->
  <follow-dialog
    v-model:visible="addTaskDialogVisible"
    :mode="'create'"
    :task-data="[]"
  />

  <!-- 报告对比抽屉 -->
  <ReportCompareDrawer
    v-model="showCompareDrawer"
    :currentReport="currentReport"
  />
  <!-- 风险评估 -->
  <!-- <RiskAssessment
    v-model="showCompareDrawer"
    :report-id="1210"
    :report-type="1"
    @submit-success="handleRiskAssessmentSubmit"
  /> -->
  <!--  @submit="handleRiskAssessmentSubmit" -->
</template>

<script setup lang="ts">
import { reportApi } from "@/api/report-api";
// import AddTask from "@/components/AddTask/index.vue";
import ImagingDataModal from "@/components/ImagingDataModal/index.vue";
import JiankangDrawer from "@/components/jiankang/index.vue";
import { PAGE_SIZE } from "@/constants/common-const";
import { useToolsStore } from "@/store/modules/tools";
import { attentionTypeList as commonAttentionTypeList } from "@/utils/tools";
import FollowDialog from "@/views/followUpPlan/components/followDialog.vue";
import { Search } from "@element-plus/icons-vue";
import dayjs from "dayjs";
import { ElMessage } from "element-plus";
import { computed, onMounted, reactive, ref } from "vue";
import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
import ReportCompareDrawer from "./components/report-compare-drawer/index.vue";
import { ReportQueryForm } from "@/api/types";

// 初始化 store
const toolsStore = useToolsStore();
toolsStore.clearDictData();

// 查询表单初始状态
const queryFormState: ReportQueryForm = {
  userName: "",
  startDate: null,
  endDate: null,
  riskLevelId: null,
  healthCategoryId: null,
  statusId: null,
  attentionType: null,
  medicalInstitution: "",
  healthTagId: null,
  pageNum: 1,
  pageSize: PAGE_SIZE
};

// 响应式数据
const showCompareDrawer = ref(false);
const queryForm = reactive({ ...queryFormState });
// 使用 computed 获取字典数据
const dateRange = ref([]);
const attentionTypeList = ref(commonAttentionTypeList);
// 当前选中的报告
const currentReport = ref({});
const dictData = ref(toolsStore.getDictData());

// 获取字典数据
async function queryDictionaryData() {
  try {
    const response = await reportApi.queryReportDict();
    if (response?.data) {
      dictData.value = response.data;
      toolsStore.setDictData(response.data);
    }
  } catch (err) {
    console.error("获取字典数据失败:", err);
    ElMessage.error("获取字典数据失败");
  }
}
// 表格数据
const tableData = ref();
const total = ref(1);
const tableLoading = ref(false);
const addTaskDialogVisible = ref();

// 查询报告列表
async function queryReportList() {
  tableLoading.value = true;
  try {
    const response = await reportApi.queryReportList({
      ...queryForm,
      endDate: queryForm.endDate ? dayjs(queryForm.endDate).valueOf() : null,
      startDate: queryForm.startDate
        ? dayjs(queryForm.startDate).valueOf()
        : null
    });
    if (response?.data) {
      tableData.value = response.data.list;
      total.value = response.data.total || 0;
    }
  } catch (err) {
    console.error("查询报告列表失败:", err);
    ElMessage.error("查询报告列表失败");
  } finally {
    tableLoading.value = false;
  }
}

// 搜索
function onSearch() {
  queryForm.pageNum = 1;
  queryReportList();
}

// 重置
function onReload() {
  Object.assign(queryForm, queryFormState);
  dateRange.value = [];
  queryReportList();
}

// 日期范围变化
function onDateChange(dates) {
  if (dates && dates.length === 2) {
    queryForm.startDate = dates[0];
    queryForm.endDate = dates[1];
  } else {
    queryForm.startDate = null;
    queryForm.endDate = null;
  }
}

// 路由
const router = useRouter();

// I18n
const { t } = useI18n();
// 查看报告
function viewReport(reportId) {
  router.push({
    path: "/report/detail",
    query: { reportId, mode: "view" }
  });
}

// 报告对比
function compareReport(report) {
  currentReport.value = report;
  console.log("showCompareDrawer", showCompareDrawer.value);
  showCompareDrawer.value = true;
}

// 填写建议
function writeSuggestion(reportId) {
  router.push({
    path: "/system/report/suggestion",
    query: { reportId }
  });
}

// 加入任务
function addToTask(report) {
  addTaskDialogVisible.value = true;

  // ElMessageBox.confirm("确认将此报告加入任务列表吗？", "确认操作", {
  //   confirmButtonText: "确定",
  //   cancelButtonText: "取消",
  //   type: "warning"
  // })
  //   .then(() => {
  //     // TODO: 调用加入任务的API
  //     ElMessage.success("已成功加入任务列表");
  //   })
  //   .catch(() => {
  //     // 用户取消操作
  //   });
}

// 查看家庭报告
function viewReportTrack(familyId) {
  router.push({
    path: "/report/family",
    query: { familyId }
  });
}

// 显示影像资料弹窗
const imagingModalRef = ref(null);
function showImagingModal(report) {
  currentReport.value = report;
  // 调用子组件的open方法显示弹窗
  imagingModalRef.value?.open(report.reportId);
}

// 健康信息抽屉相关
const jiankangDrawerRef = ref();
function showHealthInfo(report) {
  currentReport.value = report;
  jiankangDrawerRef.value?.open(report.reportId);
}

// 处理健康信息保存
function onHealthInfoSave(data) {
  console.log("保存健康信息:", data);
  ElMessage.success("健康信息保存成功");
}

// 处理健康信息保存
function onAddTaskSave(data) {
  console.log("保存健康信息:", data);
  ElMessage.success("添加随访计划成功");
}

// 检测异常指标是否会超过两行显示
function checkIfOverflow(abnormalIndicators) {
  if (!abnormalIndicators || abnormalIndicators.length === 0) {
    return false;
  }

  // 基于指标数量和名称长度的简单估算
  // 列宽200px，每个指标大概占用的宽度
  const containerWidth = 180; // 留一些padding空间
  const itemPadding = 16; // 每个item的padding + margin
  let currentRowWidth = 0;
  let rowCount = 1;

  for (const item of abnormalIndicators) {
    // 估算每个指标名称的显示宽度 (中文字符按12px字体大小计算)
    const itemName = item.name || "";
    const itemWidth = itemName.length * 12 + itemPadding + 16; // 16是背景padding

    if (currentRowWidth + itemWidth > containerWidth) {
      // 需要换行
      rowCount++;
      currentRowWidth = itemWidth;

      if (rowCount > 2) {
        console.log(
          `异常指标超过两行显示，总共 ${abnormalIndicators.length} 项指标`
        );
        return true;
      }
    } else {
      currentRowWidth += itemWidth;
    }
  }

  return false;
}
// 组件挂载时初始化数据
onMounted(() => {
  if (router.currentRoute.value.query.isHasDate) {
    // 获取最近一周的时间范围，并设置到 dateRange 和查询表单
    // 详细日志输出，便于后续排查
    const today = dayjs().format("YYYY-MM-DD");
    const lastWeek = dayjs().subtract(6, "day").format("YYYY-MM-DD"); // 最近7天，包括今天
    dateRange.value = [lastWeek, today];
    // 将日期范围转为毫秒级时间戳（数字类型），并详细日志输出
    queryForm.startDate = dateRange.value[0]
      ? dayjs(dateRange.value[0]).valueOf()
      : null;
    queryForm.endDate = dateRange.value[1]
      ? dayjs(dateRange.value[1]).valueOf()
      : null;
  }
  queryDictionaryData();
  queryReportList();
});
</script>

<style scoped lang="scss">
/* 页面容器 - 抵消 main-content 的 margin */

/* 搜索表单 */
.search-form {
  padding: 20px;
  margin-bottom: 16px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgb(0 0 0 / 10%);
}

.search-form :deep(.el-form-item) {
  margin-right: 16px;
  margin-bottom: 16px;
}

/* 表格卡片 */
.table-card {
  border-radius: 8px;
  box-shadow: 0 2px 4px rgb(0 0 0 / 10%);
}

.table-card :deep(.el-card__body) {
  padding: 20px;
}
/* 分页容器 */
.pagination-container {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  padding: 0 40px;
  margin-top: 16px;
}
.el-tag--success {
  background: linear-gradient(138deg, #6effb9 0%, #6fff7f 100%);
  border-radius: 4px;
  color: #333;
}
.abnormalIndicators-name {
  background: #fff2f4;
  border-radius: 4px;
  padding: 2px 8px;
  font-size: 12px;
  color: #222222;
  line-height: 16px;
  margin: 6px 0;
  white-space: nowrap;
}

.actions-container {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  .el-button {
    margin-bottom: 10px;
    margin-left: 10px;
    width: 100%;
    display: flex;
    justify-content: flex-start;
  }
}
.abnormal-indicators-container {
  position: relative;
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
  max-height: 48px; /* 限制最大高度为两行(每行约24px) */
  overflow: hidden;
  line-height: 24px;

  .abnormal-indicators-item {
    margin-right: 8px;
    margin-bottom: 4px;
    flex-shrink: 0; /* 防止项目被压缩 */
  }

  /* 超过两行时的省略号效果 */
  &::after {
    content: "";
    position: absolute;
    bottom: 0;
    right: 0;
    width: 20px;
    height: 24px;
    // background: linear-gradient(to right, transparent, #fff 70%);
  }

  /* 当内容超过两行时显示省略号 */
  &.has-overflow::after {
    content: "...";
    // background: #fff;
    color: #909399;
    font-size: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: normal;
  }
}
</style>
